package com.itheima.aspect;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.util.CurrentHolder;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;


    @Around("execution(* com.itheima.service.*Service.*(..)) && @annotation(com.itheima.commons.LogOperation)")
    public Object recordOperateLog(ProceedingJoinPoint pjp) throws Throwable{
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        long costTime = end - start;

        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());//用户id
        operateLog.setOperateTime(LocalDateTime.now());//时间
        operateLog.setClassName(pjp.getTarget().getClass().getName());//类名
        operateLog.setMethodName(pjp.getSignature().getName());//方法名
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));//方法参数
        operateLog.setCostTime(costTime);//方法耗时
        operateLog.setReturnValue(result + "");//方法返回值
        operateLogMapper.insert(operateLog);
        return result;
    }
}
